package com.wj.utils;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt 工具类
 * @author wj
 * @since 1.0.0
 * */
@Component
public class JwtUtil {
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATE = "created";
    @Value("${jwt.expiration}")
    private Long expiration;
    @Value("${jwt.secret}")
    private String secret;

    /**
     * 根据用用户信息生成Token
     * @Param claims
     * @return
     * */
    public String generateToken(UserDetails userDetails){
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME,userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATE,new Date());
        return generateToken(claims);
    }

    /**
     * 根据jwt负载生成Token，设置过期时间和秘钥
     * */
    private String generateToken(Map<String,Object> claims){
        return Jwts.builder().addClaims(claims).signWith(SignatureAlgorithm.HS256,secret)
                .setExpiration(new Date(System.currentTimeMillis()+expiration*1000)).compact();
    }

    /**
     * 从token获取登录用户名
     * @param token
     * @return
     * */
    public String getUserNameFromToken(String token){
        String username;
        try {
            Claims claims = getClaimFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username=null;
        }
        return username;
    }

    /**
     * 从token中获取荷载
     * @param token
     * @return
     * */
    private Claims getClaimFromToken(String token) {
        Claims claims=null;
        try {
            claims=Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;
    }

    /**
     * 判断token是否有效
     * @param token
     * @param userDetails
     * @return
     * */
    public boolean validateToken(String token,UserDetails userDetails){
        return userDetails.getUsername().equals(getUserNameFromToken(token)) && !isTokenExpired(token);
    }

    /**
     * 判断token时间是否过期
     * @param  token
     * @return
     * */
    private boolean isTokenExpired(String token) {
        Date expiration = getClaimFromToken(token).getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 判断token是否可以被刷新
     * @param token
     * @return
     * */
    public boolean canRefresh(String token){
        return !isTokenExpired(token);
    }

    /**
     * 刷新token时间
     * @param token
     * @return
     * */
    public String refreshToken(String token){
        Claims claim = getClaimFromToken(token);
        claim.put(CLAIM_KEY_CREATE,new Date());
        return generateToken(claim);
    }
}
